home *** CD-ROM | disk | FTP | other *** search
- Path: newshost.lanl.gov!tanmoy
- From: tanmoy@qcd.lanl.gov (Tanmoy Bhattacharya)
- Newsgroups: comp.lang.c
- Subject: Re: revised code of calling a function twice from printf
- Date: 05 Mar 1996 03:44:09 GMT
- Organization: Los Alamos National Laboratory
- Distribution: world
- Message-ID: <TANMOY.96Mar4204409@qcd.lanl.gov>
- References: <4hfs54$k4e@newsbf02.news.aol.com>
- <Pine.A32.3.91.960304174215.96209J-100000@black.weeg.uiowa.edu>
- NNTP-Posting-Host: qcd.lanl.gov
- Mime-Version: 1.0
- Content-Type: text
- In-reply-to: The Amorphous Mass's message of Mon, 4 Mar 1996 17:51:03 -0600
-
- In article <Pine.A32.3.91.960304174215.96209J-100000@black.weeg.uiowa.edu>
- The Amorphous Mass <robinson@blue.weeg.uiowa.edu> writes:
- <snip>
- TAM: You're returning a pointer to an automatic variable, which is
- TAM: guaranteed bad news.
- <snip>
- TAM: printf("[1] %s [2] %s\n", /* both quotes on same line */
- TAM: display_drug_type(0), display_drug_type(1));
- <snip>
- TAM: > char *display_drug_type(int drug_index) {
- <snip>
- TAM: static char drug_type[81]; /* static variables are automatically
- TAM: initialized to 0, and it's safe to
- TAM: return their addresses -- they "persist" */
- <snip>
- TAM: > return drug_type;
- TAM: > }
-
- The program is still incorrect. No solution `works' and avoids memory
- leak without changing the call. So, simply use,
-
- char first[80]={0}, second[80]={0};
- strncpy(first,display_drug_type(0),sizeof first - 1);
- strncpy(second,display_drug_type(1),sizeof second - 1);
- printf("[1] %s [2] %s\n",first,second);
-
- Many other solutions are possible: some cleaner than others. I would
- actually use malloc/free in this context.
-
- Cheers
- Tanmoy
- --
- tanmoy@qcd.lanl.gov(128.165.23.46) DECNET: BETA::"tanmoy@lanl.gov"(1.218=1242)
- Tanmoy Bhattacharya O:T-8(MS B285)LANL,NM87545 H:#9,3000,Trinity Drive,NM87544
- Others see <gopher://yaleinfo.yale.edu:7700/00/Internet-People/internet-mail>,
- <http://alpha.acast.nova.edu/cgi-bin/inmgq.pl>or<ftp://csd4.csd.uwm.edu/pub/
- internetwork-mail-guide>. -- <http://nqcd.lanl.gov/people/tanmoy/tanmoy.html>
- fax: 1 (505) 665 3003 voice: 1 (505) 665 4733 [ Home: 1 (505) 662 5596 ]
-